package face.pay.common.quota.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import face.pay.common.quota.service.IQuotaApplyService;
import face.pay.constant.ProfitStrategy;
import face.pay.constant.UserType;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.server.IOemProfitConfigServer;
import face.pay.util.MathUtil;
import face.pay.util.ResultMessage;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Auther: zkj
 * @Date: 2019/7/18 14:46
 * @Description:
 */
@Service
@Slf4j
public class QuotaApplyServiceImpl implements IQuotaApplyService {

    @Autowired
    AgencyQuotaDao agencyQuotaDao;

    @Autowired
    AgencyQuotaApplyDao agencyQuotaApplyDao;

    @Autowired
    AgencyLevelDao agencyLevelDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private IncomeInfoDao incomeInfoDao;

    @Autowired
    private UserInfoDao userInfoDao;


    @Autowired
    private IOemProfitConfigServer oemProfitConfigServer;


    private ResultMessage passApply(AgencyQuotaApply agencyQuotaApply, UserInfo loginUser) {

        log.info("OEM 商户 确认代理名额申请");
        AgencyQuotaApply apply = this.agencyQuotaApplyDao.getById(agencyQuotaApply.getId());

        Integer status = apply.getStatus();
        if(new Integer(0).equals(status)){
            log.info("名额申请记录未处理 准备处理");
            Integer levelId = apply.getLevelId();

            Integer applyUserId = apply.getApplyUserId();

            Integer oemId  = loginUser.getOemId();

            apply.setUpdatedBy(loginUser.getId());
            apply.setStatus(agencyQuotaApply.getStatus());
            apply.setMessage(agencyQuotaApply.getMessage());
            /**
             * 修改apply 状态
             */
            log.info("更新申请状态");

            this.agencyQuotaApplyDao.upStatus(apply);

            /**
             * 增加代理商对应等级 的名额
             * 保存日志
             */
            log.info("查找 agencylevel:"+levelId+" applyUserId:"+applyUserId+"配额 情况");
            AgencyQuota agencyQuota = this.agencyQuotaDao.getQuotaByUserIdAndLevelId(applyUserId,levelId);
            Integer  quantity = apply.getQuantity()==null?0:apply.getQuantity();

            if(agencyQuota==null){

                log.info("agencyQuota 不存在");

                agencyQuota = new AgencyQuota();
                agencyQuota.setUserId(applyUserId);
                agencyQuota.setLevelId(levelId);
                agencyQuota.setOemId(oemId);
                agencyQuota.setQuantity(quantity);
                agencyQuota.setCreatedBy(loginUser.getId());

                this.agencyQuotaDao.insert(agencyQuota);

                log.info("插入 agencyQuota ");

            }else {
                log.info("更新 agencyQuota ");

                agencyQuota.setQuantity(apply.getQuantity());
                agencyQuota.setUpdatedBy(loginUser.getId());
                this.agencyQuotaDao.addquantity(agencyQuota);
            }
            log.info("开始录入收益");
            /**
             * 购买名额对应等级
             */
            AgencyLevel agencyLevel = this.agencyLevelDao.getById(levelId);

            Long price =  agencyLevel.getPrice();

            if(price.compareTo(new Long(1))==1){

                Long totalPrice = price*quantity;

                OemInfo oemInfo =  this.oemInfoDao.getOemInfoById(oemId);

                OemProfitConfigInfo oemProfitConfigInfo = this.oemProfitConfigServer.getOemProfitConfig(oemId);

                Long totalMoney =  new BigDecimal(totalPrice.toString()).longValue();
                log.info("名额价格 "+totalMoney);
                Long totalProfit = 0L;

                UserInfo applyUser = this.userInfoDao.getById(applyUserId);
                /**
                 * 名额购买者对应的等级
                 */
                AgencyLevel applyAgencyLevel = this.agencyLevelDao.getById(applyUser.getLevelId());

                log.info("oem分润策略为 DEFAULT");

                Double levelProfit =  applyAgencyLevel.getDirectRecAgencyProfit();

                Long profit = MathUtil.profit(totalMoney,levelProfit);

                IncomeInfo incomeInfo =  new IncomeInfo(applyUserId,oemId,profit,IncomeInfo.TYPE.AGENCY_REC,Long.valueOf(apply.getId()));

                /**
                 * 插入收入
                 */
                incomeInfo.setCreatedBy(loginUser.getId());

                log.info("插入购买用户收入表");
                incomeInfoDao.insert(incomeInfo);
                totalProfit = totalProfit+profit;


                if(ProfitStrategy.PERCENTAGE.equals(oemProfitConfigInfo.getProfitStrategy())){

                    log.info("oem 分润策略为 PERCENTAGE");
                    /**
                     * PERCENTAGE 策略
                     */
                    Integer parId = loginUser.getId();
                    UserInfo parUser =userInfoDao.getById(parId);
                    if(UserType.AGENCY.equals(parUser.getType())){

                        Double indirectLevelProfit =  applyAgencyLevel.getIndirectRecAgencyProfit();

                        Long indirecProfit = MathUtil.profit(totalMoney,indirectLevelProfit);

                        if(indirecProfit.compareTo(new Long(1))==1){
                            IncomeInfo indirectIncomeInfo =  new IncomeInfo(parId,oemId,indirecProfit,IncomeInfo.TYPE.AGENCY_REC,Long.valueOf(apply.getId()));
                            incomeInfoDao.insert(indirectIncomeInfo);
                            totalProfit = totalProfit+indirecProfit;
                        }
                    }
                }

                /**
                 * oem 收入插入
                 */
                Long oem_profit =totalMoney-totalProfit;


                IncomeInfo oemincomeInfo =  new IncomeInfo(loginUser.getId(),oemId,oem_profit,IncomeInfo.TYPE.AGENCY_REC,Long.valueOf(apply.getId()));

                oemincomeInfo.setCreatedBy(loginUser.getId());
                incomeInfoDao.insert(oemincomeInfo);
                log.info("插入oem用户收入表");
            }else {
                log.info("购买等级 价格太小 分佣终止");
                return ResultMessage.createSuccess("处理成功");
            }

        }else {
          return     ResultMessage.createFail("数据已经被处理");
        }
        return ResultMessage.createSuccess("处理成功");
    }

    private ResultMessage rejectApply(AgencyQuotaApply agencyQuotaApply, UserInfo loginUser) {
        log.info("代理商");
        agencyQuotaApply.setUpdatedBy(loginUser.getId());
        this.agencyQuotaApplyDao.upStatus(agencyQuotaApply);
        return ResultMessage.createSuccess();
    }


    @Override
    public PageData<AgencyQuotaApply> queryList(AgencyQuotaApply agencyQuotaApply, PageParam pageParam) {

        PageHelper.startPage(pageParam.getPageNo(),pageParam.getPageSize());

        List<AgencyQuotaApply> agencyQuotas = this.agencyQuotaApplyDao.queryDetails(agencyQuotaApply);

        PageInfo<AgencyQuotaApply> pageInfo = new PageInfo <AgencyQuotaApply>(agencyQuotas);

        PageData<AgencyQuotaApply> pageData = new PageData<AgencyQuotaApply>(pageInfo.getTotal(),agencyQuotas);

        return pageData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage applyHandle(AgencyQuotaApply agencyQuotaApply, UserInfo loginUser) {

        Integer status = agencyQuotaApply.getStatus();
        if(new Integer(1).equals(status)){
            return  this.passApply(agencyQuotaApply,loginUser);
        }else {
            return  this.rejectApply(agencyQuotaApply,loginUser);
        }
    }


    /**
     * oem 商户直接向代理添加名额
     * @param agencyQuotaApply
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage addQuota(AgencyQuotaApply apply, UserInfo loginUser)
    {

        Integer oemId = loginUser.getOemId();

        apply.setCreatedBy(loginUser.getId());
        apply.setType(AgencyQuotaApply.TYPE.SYSTEM);
        apply.setOemId(oemId);
        apply.setStatus(1);//直接通过
        apply.setMessage("系统赠送");
        this.agencyQuotaApplyDao.insert(apply);

        Integer applyId = apply.getId();

        Integer levelId = apply.getLevelId();

        Integer applyUserId = apply.getApplyUserId();



        log.info("查找 agencylevel:"+levelId+" applyUserId:"+applyUserId+"配额 情况");
        AgencyQuota agencyQuota = this.agencyQuotaDao.getQuotaByUserIdAndLevelId(applyUserId,levelId);
        Integer  quantity = apply.getQuantity()==null?0:apply.getQuantity();

        if(agencyQuota==null){

            log.info("agencyQuota 不存在");

            agencyQuota = new AgencyQuota();
            agencyQuota.setUserId(applyUserId);
            agencyQuota.setLevelId(levelId);
            agencyQuota.setOemId(oemId);
            agencyQuota.setQuantity(quantity);
            agencyQuota.setCreatedBy(loginUser.getId());

            this.agencyQuotaDao.insert(agencyQuota);

            log.info("插入 agencyQuota ");

        }else {
            log.info("更新 agencyQuota ");

            agencyQuota.setQuantity(apply.getQuantity());
            agencyQuota.setUpdatedBy(loginUser.getId());
            this.agencyQuotaDao.addquantity(agencyQuota);
        }

        /**
         * 不计入收入
         */

        return ResultMessage.createSuccess();
    }

}
